package com.thread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class JUC_tatao_interview_Semaphore_23 {

    volatile static List<Object> list = new ArrayList<>();

    void add(Object o){
        list.add(o);
    }
    int size(){
        return list.size();
    }
    static Thread t2 = null;static Thread t1=null;
    public static void main(String[] args) {
        Semaphore s = new Semaphore(1);
        JUC_tatao_interview_Semaphore_23 t = new JUC_tatao_interview_Semaphore_23();
        t1 = new Thread(()->{
            try {
                s.acquire();//阻塞其他线程
                for(int i=0;i<5;i++){
                    System.out.println("add "+i);
                    list.add(new Object());
                }
                s.release();//释放锁
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            t2.start();;
            try {
                t2.join();//等t2执行完
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            try {
                s.acquire();//阻塞其他线程
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            for(int i=5;i<10;i++){
                System.out.println("add "+i);
                list.add(new Object());
            }
        });


        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        t2 = new Thread(()->{
            try {
                s.acquire();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+":size"+t.size());
            //释放锁
            s.release();
        },"t2");

        t1.start();
    }
}
